<template>
    <!-- 头部工具栏 -->
    <Toolbar :actions="[leftActions, rightActions]">
        <template #[item]="data" v-for="item in toolbarSlots" :key="item">
            <slot :name="item" v-bind="data ?? {}">
                <template v-if="item === 'toolbarRight'">
                    <!-- <FilterView :data="[]" /> -->
                </template>
            </slot>
        </template>
    </Toolbar>
    <!-- 表格主体 -->
    <div class="getan-table-content">
        <n-data-table
            ref="tableRef"
            v-bind="mergedProps"
            :pagination="pagination"
            @update:page="handleUpdatePage"
            @update:page-size="handleUpdatePageSize"
            @update:sorter="handleSorterChange"
        >
            <template #[item]="data" v-for="item in ['empty', 'loading']" :key="item">
                <slot :name="item" v-bind="data ?? {}"></slot>
            </template>
        </n-data-table>
    </div>
</template>

<script setup lang="ts">
import Toolbar from "./components/Toolbar.vue"
import { isEmpty, isUndefined, log } from "@/utils"
import { useColumns } from "./hooks/useColumns"
import { useDataSource } from "./hooks/useDataSource"
import { useLoading } from "./hooks/useLoading"
import { usePagination } from "./hooks/usePagination"
import { DataTableMethods, GetanTableProps } from "./types"
import { useToolbarActions } from "./hooks/useToolbarActions"
import { useFlexHeight } from "./hooks/useFlexHeight"
import { useSummary } from "./hooks/useSummary"
import { useSorter } from "./hooks/useSorter"
import { useFilter } from "./hooks/useFilter"
import { OrderBy } from "@/constant/types"
import { useRowSelect } from "./hooks/useRowSelect"

const props = defineProps<{ options?: GetanTableProps }>()
const attrs = useAttrs()
const propsRef = ref<Partial<GetanTableProps>>({})

const tableRef = ref(null)

// 解释 options
const mergedOptions = computed((): Partial<GetanTableProps> => {
    return {
        ...(props.options ?? {}),
        ...unref(propsRef)
    }
})
const { loading, setLoading } = useLoading()
const { tableData, setTableData, getTableData } = useDataSource()
const { getSorterParams, setSorter, sorter } = useSorter(mergedOptions)
const { getFilterParams, setFilterConditions } = useFilter(mergedOptions)
const { columns, showColumns } = useColumns(mergedOptions, sorter)
const { clearChecked, rowKeyFunction } = useRowSelect(mergedOptions)
const { pagination, changePageNum, changePageSize, getPageParams, setPagination } = usePagination(mergedOptions)
const { leftActions, rightActions, toolbarSlots } = useToolbarActions(mergedOptions)
const { deviceHeight } = useFlexHeight(tableRef, mergedOptions)
const { summary, setSummaryData, hasSummary } = useSummary(mergedOptions, columns, showColumns)

const mergedProps = computed(() => {
    return Object.assign(
        {},
        !isEmpty(unref(mergedOptions))
            ? {
                  rowKey: unref(rowKeyFunction),
                  remote: !isUndefined(unref(mergedOptions).request),
                  loading: unref(loading),
                  data: unref(tableData),
                  columns: unref(showColumns),
                  //   pagination,
                  maxHeight: unref(mergedOptions).useFlexHeight ? unref(deviceHeight) : undefined,
                  bordered: true,
                  summary: hasSummary.value ? summary : undefined
              }
            : {},
        attrs
    ) as Recordable
})

/**
 * 分页
 */
const handleUpdatePage = (page: number) => {
    if (loading.value) {
        return false
    }
    changePageNum(page)
    loadData()
}

/**
 * 调整每页显示行数
 */
const handleUpdatePageSize = (pageSize: number) => {
    if (loading.value) {
        return false
    }
    changePageSize(1, pageSize)
    loadData()
}

/**
 * 重排序
 */
const handleSorterChange = (option: { columnKey: string; sorter: boolean; order: string | boolean }) => {
    if (loading.value) {
        return false
    }
    if (option.order === false) {
        setSorter()
    } else {
        setSorter({ property: option.columnKey, order: option.order as OrderBy })
    }
    changePageNum(1)
    loadData()
}

/**
 * 远程加载数据
 */
const loadData = async () => {
    const { request } = unref(mergedOptions)
    if (!request) {
        return false
    }
    if (loading.value) {
        return false
    }
    try {
        setLoading(true)
        const params: Recordable = {}
        // 排序
        getSorterParams(params)
        // 过滤
        getFilterParams(params)
        // 分页
        if (pagination.value) {
            getPageParams(params)
        }
        console.log(params)
        clearChecked()
        const { isOk, res } = await request(params)
        if (isOk()) {
            // 使用分页
            if (pagination.value) {
                res.value.totalRow = res.value.totalRow * 1
                setPagination(res.value)
                setTableData(res.value.rows as Recordable[])
                setSummaryData(res.value.summary)
            } else {
                setTableData(res.value as Recordable[])
            }
        }
    } catch (e) {
        log.error("数据加载失败：" + e)
        setTableData([])
    } finally {
        setLoading(false)
    }
}

onMounted(() => {
    // setTimeout(() => {
    loadData()
    // }, 16)
})

const emits = defineEmits(["register"])

function init(registerProps: Partial<GetanTableProps>) {
    propsRef.value = registerProps ?? {}
}

const methods: DataTableMethods = {
    init,
    loadData,
    setTableData,
    getTableData,
    setFilterConditions
}

const instance = getCurrentInstance()
if (instance) {
    emits("register", methods)
}
</script>
